package com.novel.controller.other;

import com.novel.common.enums.UserIdentifyEnum;
import com.novel.common.exception.CustomerException;
import com.novel.common.pojo.RedisParamKey;
import com.novel.pojo.novel.Novel;
import com.novel.pojo.novel.NovelChapter;
import com.novel.pojo.novel.NovelShelf;
import com.novel.pojo.system.ApplyAuthor;
import com.novel.pojo.system.User;
import com.novel.service.*;
import com.novel.utils.FileUploadUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Controller
public class JumpController extends BaseController {

    @Autowired
    private NovelCategoryService categoryService;

    @Autowired
    private NovelService novelService;

    @Autowired
    private UserService userService;

    @Autowired
    private NovelShelfService shelfService;

    @Autowired
    private NovelChapterService chapterService;

    @Autowired
    private ChapterOrderService chapterOrderService;

    @Autowired
    private ApplyAuthorService applyAuthorService;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @Autowired
    private OrderService orderService;

    /**
     * 跳转到用户订单列表页面
     */
    @GetMapping("/personal/order/list")
    public ModelAndView getPersonalOrderList(ModelAndView mv,
                                             @RequestParam(required = false, defaultValue = "1") Integer pageNum) {
        User user = getUserInformation();

        if (Objects.isNull(user)) {
            mv.setViewName("redirect:/login");
        } else {
            mv.addObject("pageInfo", orderService.queryOrderByUserAndPage(user.getUserId(), pageNum, 10));
            mv.setViewName("personal/order_list");
        }
        return mv;
    }

    /**
     * 跳转到修改头像页面
     */
    @GetMapping("change/img")
    public ModelAndView changeImg(ModelAndView mv) {
        if (Objects.isNull(getUserInformation())) {
            mv.setViewName("login");
        } else {
            mv.setViewName("personal/change_img");
        }
        return mv;
    }

    @PostMapping("change/user/img")
    public ModelAndView uploadImg(MultipartFile file, ModelAndView mv) throws Exception {

        User user = getUserInformation();
        if (user == null) {
            mv.setViewName("redirect:/login");
            return mv;
        }
        //图片上传
        String imgUrl = fileUploadUtil.upload(file);

        if (StringUtils.isBlank(imgUrl)) {
            throw new CustomerException("文件上传失败!");
        }
        //更新用户信息
        userService.updateUserImgSrc(imgUrl, user);
        mv.setViewName("redirect:/personal");
        return mv;
    }


    /**
     * 跳转到充值界面
     * 必须登录者才能跳转到充值界面
     */
    @GetMapping("recharge")
    public ModelAndView toRecharge(ModelAndView mv) {
        if (Objects.isNull(getUserInformation())) {
            mv.setViewName("login");
        } else {
            //查询充值信息
            mv.addObject("itemList", getRechargeInfo());
            mv.setViewName("payment/payInfo");
        }
        return mv;
    }


    /**
     * 项目的入口，因为thymeleaf只能通过控制器来访问
     * 1.需要查询网站有那些作品分类信息
     * 2.需要查询网站目前有那些小说，只需要查询基本信息即可
     *
     * @param mv 要跳转的页面和携带的参数
     */
    @GetMapping(value = {"/", "/index"})
    public ModelAndView toIndex(ModelAndView mv,
                                @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                @RequestParam(required = false, defaultValue = "12") Integer pageSize,
                                @RequestParam(required = false) String category,
                                @RequestParam(required = false, defaultValue = "0") Integer viewType) {
        //查询所有分类信息，并把信息保存到请求域中
        mv.addObject("categoryList", categoryService.findAllCategory());
        //查询所有小说信息，并把信息保存到请求域中
        //默认查询第一页，页大小为12
        mv.addObject("novelList", novelService.findAllNovelByPage(pageNum, pageSize, category));
        //设置页面展示的方式 0:图片形式 1:文字形式
        mv.addObject("viewType", viewType);
        //设置要跳转的页面
        mv.setViewName("index/index");
        return mv;
    }


    /**
     * 跳转到个人信息查看页面
     */
    @GetMapping("/personal")
    public ModelAndView personal(ModelAndView mv) {
        User user = getUserInformation();
        if (user != null) {
            mv.setViewName("/personal/personal");
            //重新查询一次个人信息避免，信息更新不及时
            setUserInformation(userService.Login(user.getUserEmail(), user.getPassword()));
        } else {
            mv.setViewName("login");
        }
        return mv;
    }

    /***
     * 跳转到修改个人信息界面
     */
    @GetMapping("/change/info")
    public ModelAndView changeInfo(ModelAndView mv) {
        User user = getUserInformation();
        if (user != null) {
            mv.setViewName("/personal/changeinfo");
        } else {
            mv.setViewName("login");
        }
        return mv;
    }

    /**
     * 跳转到验证新旧密码修改密码界面
     */
    @GetMapping("/change/password")
    public ModelAndView changePassword(ModelAndView mv) {
        User user = getUserInformation();
        if (user != null) {
            mv.setViewName("/password/password");
        } else {
            mv.setViewName("login");
        }
        return mv;
    }

    /**
     * 跳转到注册成为作家界面
     */
    @GetMapping("/change/author")
    public ModelAndView changeToBeAuthor(ModelAndView mv) {
        User user = getUserInformation();
        if (user == null) {
            mv.setViewName("redirect:/login");
            return mv;
        }

        if (checkUserPermission(UserIdentifyEnum.AUTHOR, user.getIdentify())) {
            mv.setViewName("redirect:/author/index");
        } else {
            //查询用户是否有申请记录有的话，展示申请记录
            ApplyAuthor applyAuthorInfo = applyAuthorService.findApplyAuthorInfo(user.getUserId());
            mv.addObject("applyInfo", applyAuthorInfo);
            mv.setViewName("/personal/toBeAuthor");
        }
        return mv;
    }

    /**
     * 跳转到根据邮箱验证修改密码界面
     */
    @GetMapping("/change/email")
    public ModelAndView changePasswordEmail(ModelAndView mv) {
        User user = getUserInformation();
        if (user != null) {
            mv.setViewName("/password/email");
        } else {
            mv.setViewName("login");
        }
        return mv;
    }

    /**
     * 跳转到登录页面
     */
    @GetMapping("/login")
    public ModelAndView login(ModelAndView mv) {
        User user = getUserInformation();

        if (user == null) {
            mv.setViewName("login");
        } else {
            mv.setViewName("redirect:/index");
        }
        return mv;
    }

    /**
     * 跳转到书架页面，并且查询对应的书架信息
     */
    @GetMapping("/shelf")
    public ModelAndView shelf(ModelAndView mv) {
        User user = getUserInformation();
        if (user == null) {
            //跳转到登录页面
            mv.setViewName("login");
        } else {
            //查询小说数据
            List<Novel> novelList = shelfService.findNovelByUserId(user.getUserId());
            //保存数据到请求域中
            mv.addObject("novelList", novelList);
            mv.setViewName("shelf/shelf");
        }
        return mv;
    }

    /**
     * 跳转到小说阅读界面
     *
     * @param novelId      小说id
     * @param chapterOrder 章节序号
     */
    @GetMapping("/chapter/read/{novelId}/{chapterOrder}")
    public ModelAndView readById(ModelAndView mv,
                                 @PathVariable("novelId") String novelId,
                                 @PathVariable("chapterOrder") Integer chapterOrder) {
        //获取用户信息
        User user = getUserInformation();
        if (user != null) {
            //查询用户的书架，这个书籍是否在书架中
            List<NovelShelf> shelf = shelfService.findUserShelf(user.getUserId());
            //获取小说id集合
            List<String> ids = shelf.stream().map(NovelShelf::getNovelId).collect(Collectors.toList());
            if (ids.contains(novelId)) {
                //这本小说在书架中，需要更新书架上的信息
                NovelShelf novelShelf = new NovelShelf();
                novelShelf.setUserId(user.getUserId());
                novelShelf.setNovelId(novelId);
                if (chapterOrder == 0) {
                    chapterOrder = 1;
                }
                novelShelf.setChapterOrder(chapterOrder);
                shelfService.updateShelf(novelShelf);
            }
        }
        //查询章节信息
        NovelChapter chapter = chapterService.findChapterByNovelAndOrder(novelId, chapterOrder);
        if (chapter != null) {
            //校验是否可以阅读
            if (chapter.getVip() == 1) {
                if (user == null) {
                    chapter.setChapterContent("请登录后阅读!");
                } else if (!chapterOrderService.checkUserIsAuthor(novelId, user.getUserId()) && !chapterOrderService.checkUserBuyChapter(chapter.getChapterId(), user.getUserId())) {
                    chapter.setChapterContent("你还没有购买该章节! 请购买后阅读");
                }
            } else {
                redisUtils.hashIncrSum(novelId, RedisParamKey.novelClick);
            }
            //把章节信息保存到请求域中
            mv.addObject("chapter", chapter);
            //跳转到对应的页面
            mv.setViewName("chapter/read");
        } else {
            mv.setViewName("forward:/chapter/info/" + novelId);
        }
        return mv;
    }

    /**
     * 根据小说id，查询小说的详细信息
     *
     * @param id 小说id
     */
    @GetMapping("/chapter/info/{id}")
    public ModelAndView chapterInfoById(ModelAndView mv, @PathVariable("id") String id) {
        //设置返回的页面
        mv.setViewName("chapter/info");
        //设置携带的数据
        mv.addObject("novel", novelService.findNovelById(id));
        //查询最后一章小说章节内容
        List<NovelChapter> list = chapterService.findChapterList(id);

        if (CollectionUtils.isNotEmpty(list)) {
            mv.addObject("chapter", list.get(list.size() - 1));
        }
        return mv;
    }

    /**
     * 注销
     */
    @GetMapping("/logout")
    public ModelAndView logout(ModelAndView mv) {
        clearUserInformation();
        mv.setViewName("redirect:/index");//页面跳转到首页
        return mv;
    }

    /**
     * 跳转到小说章节列表页面
     * 并把小说章节列表添加到请求域中
     *
     * @param id 小说id
     */
    @GetMapping("/chapter/list/{id}")
    public ModelAndView login(ModelAndView mv, @PathVariable("id") String id) {
        //添加小说章节信息
        mv.addObject("chapterList", chapterService.findChapterList(id));
        //添加小说基本信息到请求域中
        mv.addObject("novel", novelService.findNovelById(id));
        mv.setViewName("chapter/list");
        return mv;
    }


    /**
     * 根据关键词分页查询小说信息
     *
     * @param search   搜索关键词
     * @param pageNum  当前页号
     * @param pageSize 页大小
     * @param category 分类信息
     */
    @GetMapping("/search")
    public ModelAndView search(ModelAndView mv,
                               @RequestParam(required = false) String search,
                               @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                               @RequestParam(required = false, defaultValue = "12") Integer pageSize,
                               @RequestParam(required = false) String category) {
        //根据输入的内容查询对应的信息
        if (!StringUtils.isBlank(search)) {
            //查询信息
            mv.addObject("list", novelService.findNovelByName(search));
        } else {
            mv.addObject("list", novelService.findAllNovelByPage(pageNum, pageSize, category).getList());
        }
        //设置要跳转的页面
        mv.setViewName("index/search");
        return mv;
    }

    /**
     * 跳转到注册页面
     */
    @GetMapping("/signin")
    public ModelAndView signin(ModelAndView mv) {
        mv.setViewName("signin");
        return mv;
    }

    /**
     * 继续阅读按钮，查询到对应的数据之后，返回对应的数据给页面
     */
    @GetMapping("/chapter/con/read/{id}")
    public ModelAndView conRead(ModelAndView mv, @PathVariable("id") String id) {
        //获取用户信息
        User user = getUserInformation();
        //获得用户书架
        List<NovelShelf> list = shelfService.findUserShelf(user.getUserId());
        //遍历获取对应的内容
        List<Integer> result = list.stream()
                .filter(shelf -> shelf.getNovelId().equals(id))
                .map(NovelShelf::getChapterOrder)
                .collect(Collectors.toList());
        //添加数据到隐藏域中
        mv.addObject("chapter", chapterService.findChapterByNovelAndOrder(id, result.get(0)));
        //页面跳转
        mv.setViewName("chapter/read");
        return mv;
    }


}
